<?php
declare (strict_types = 1);

namespace app\wechat\controller;

class Member extends BaseController
{
    protected $token;
    protected function checkLogin()
    {
        $token = $this->request->header('authorization');
        if (!empty($token)) {
            $userInfo = session("wechat_login_{$token}");
        }
        if (empty($userInfo)) {
            $from_url = $this->request->post('location_href');
            if (empty($from_url)) {
                failure(113);
            }
            $info = parse_url($from_url);
            $current_domain = explode(':', $_SERVER['HTTP_HOST'])[0];
            if (empty($info['host']) || $info['host'] != $current_domain) {
                failure(114);
            }
            $redirect_url = make_auth_url($from_url, null, ['more' => 'xxxx']);
            failure(4, null, $redirect_url);
        }
        $this->token = $token;
        return $userInfo;
    }

    public function getApplyInfo()
    {
        $userInfo = $this->checkLogin();
        $result = [
            'nickname' => $userInfo['nickname'],
            'headimgurl' => $userInfo['headimgurl'],
            'applied' => false,
            'passed' => false,
        ];
        $bindInfo = $this->db->name('account_bind')->field('dist')->getInfo([
            'src' => $userInfo['wechatfans_id'],
            'type' => 1,
        ]);
        if (!empty($bindInfo)) {
            $result['applied'] = true;
            $userInfo = $this->db->name('member_login')->field('memberrole_id')->getInfo([
                'id' => $bindInfo['dist'],
                'deleted' => 0,
            ]);
            if (!empty($userInfo['memberrole_id'])) {
                $result['passed'] = true;
            }
        }
        success($result);
    }

    public function apply()
    {
        $userInfo = $this->checkLogin();
        $data = $this->request->post(['mobile', 'password']);
        $data['areacode'] = '86';
        $data['deleted'] = '0';
        $this->validate($data, [
            "mobile" => "require|mobile|unique:member_login,areacode^mobile^deleted",
            "password" => "require|password",
        ]);
        $bindInfo = $this->db->name('account_bind')->field('id')->getInfo([
            'src' => $userInfo['wechatfans_id'],
            'type' => 1,
        ]);
        if (!empty($bindInfo)) {
            failure(110);
        }
        $memberId = $this->db->name('member_login')->insertGetId([
            'memberrole_id' => '0',
            'mobile' => $data['mobile'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
            'nickname' => $userInfo['nickname'],
            'avatar' => $userInfo['headimgurl'],
            'enabled' => '1',
            'deleted' => '0',
        ]);
        $this->db->name('account_bind')->insert([
            'type' => 1,
            'src' => $userInfo['wechatfans_id'],
            'dist' => $memberId,
        ]);
        success();
    }

    public function refresh()
    {
        $this->checkLogin();
        session($this->token, null);
        cookie('wechat_auth', null);
        $this->checkLogin();
    }

    public function getAuthInfo()
    {
        $userInfo = $this->checkLogin();
        $data = $this->request->post(['uuid']);
        $this->validate($data, [
            'uuid' => 'require|xdigit|length:40',
        ]);
        $udid = $data['uuid'];
        $cacheId = "cache_qrcode_info_winform_{$udid}";
        $cacheData = cache($cacheId);
        if (empty($cacheData)) {
            failure(116);
        }
        $result = [
            'nickname' => $userInfo['nickname'],
            'headimgurl' => $userInfo['headimgurl'],
            'account' => '',
            'bound' => false,
            'flag' => $cacheData['flag'],
            'ip' => $cacheData['ip'],
            'location' => '未知',
        ];
        $bindInfo = $this->db->name('account_bind')->field('dist')->getInfo([
            'src' => $userInfo['wechatfans_id'],
            'type' => 1,
        ]);
        if (!empty($bindInfo)) {
            $userInfo = $this->db->name('member_login')->field('areacode,mobile')->getInfo([
                ['id', '=', $bindInfo['dist']],
                ['deleted', '=', 0],
                ['enabled', '=', 1],
                ['memberrole_id', '<>', 0],
            ]);
            if (!empty($userInfo)) {
                mask_str($userInfo['mobile'], 3, 4);
                $result['account'] = '+' . $userInfo['areacode'] . ' ' . $userInfo['mobile'];
                $result['bound'] = true;
            }
        }
        success($result);
    }

    public function confirmAuth()
    {
        $userInfo = $this->checkLogin();
        $data = $this->request->post(['uuid']);
        $this->validate($data, [
            'uuid' => 'require|xdigit|length:40',
        ]);
        $udid = $data['uuid'];
        $cacheId = "cache_qrcode_info_winform_{$udid}";
        $cacheData = cache($cacheId);
        if (empty($cacheData)) {
            failure(116);
        }
        cache($cacheId, null);
        $bindInfo = $this->db->name('account_bind')->field('dist')->getInfo([
            'src' => $userInfo['wechatfans_id'],
            'type' => 1,
        ]);
        if (empty($bindInfo)) {
            failure(117);
        }
        $userInfo = $this->db->name('member_login')->field('id')->getInfo([
            ['id', '=', $bindInfo['dist']],
            ['deleted', '=', 0],
            ['enabled', '=', 1],
            ['memberrole_id', '<>', 0],
        ]);
        if (empty($userInfo)) {
            failure(117);
        }
        $msgData = [
            'memberlogin_id' => $userInfo['id'],
        ];
        $clientInfo = [
            'fd' => $cacheData['fd'],
        ];
        $result = push_message('server_winform', 'authSuccess', $msgData, $clientInfo);
        if (!$result) {
            failure(118);
        }
        success();
    }
}
